package com.nus.fellowmark.common.filter.xss;

import com.nus.fellowmark.common.exception.RRException;
import org.apache.commons.lang.StringUtils;

/**
 * SQL injection filter
 *
 * @author Ruoyi Chen
 * @email chenruoyisz@gmail.com
 * @create 2023/2/10
 */
public class SQLFilter {

    /**
     * SQL injection filter
     * @param str  string to be verified
     */
    public static String sqlInject(String str){
        if(StringUtils.isBlank(str)){
            return null;
        }
        // remove char: '|"|;|\
        str = StringUtils.replace(str, "'", "");
        str = StringUtils.replace(str, "\"", "");
        str = StringUtils.replace(str, ";", "");
        str = StringUtils.replace(str, "\\", "");

        // convert to lowercase
        str = str.toLowerCase();

        // Invaild symbol
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"};

        // contain illegal characters
        for(String keyword : keywords){
            if(str.indexOf(keyword) != -1){
                throw new RRException("contain illegal characters");
            }
        }

        return str;
    }
}
